package com.city.parking;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.mapapi.search.core.PoiInfo;
import com.city.parking.AutoListView.OnLoadListener;
import com.city.parking.AutoListView.OnRefreshListener;
import com.city.parking.util.HttpClientUtil;
import com.city.parking.util.HttpRequest;
import com.city.parking.util.HttpResult;
import com.city.parking.util.SharePrefUtil;
import com.city.parking.util.Utils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v4.widget.DrawerLayout.DrawerListener;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class LeaseListActivity extends FragmentActivity implements
        OnClickListener, OnRefreshListener, OnLoadListener {
    private List<LeaseItem> mLeaseList = new ArrayList<LeaseItem>();
    private LeaseListAdapter mAdapter;
    private Activity me;
    private AutoListView listView;
    private final String[] mAreaArr = {"南京市"};
    private final String[] mFilterArr = {"全部", "只看出租", "只看求租", "只看我的"};
    private final String[] mFilterKey = {"all", "out", "in", "mine"};
    private final String[] mOrderArr = {"最新", "最便宜", "最早", "最贵"};
    private final String[] mOrderKey = {"date desc", "price asc", "date asc", "price desc"};
    private final int PAGE_SIZE = 10;
    private int mOrder = 0;
    private int mFilter = 0;
    private String mArea = mAreaArr[0];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        me = this;
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_parking_lease);
        TextView titleTv = (TextView) findViewById(R.id.nav_title);
        titleTv.setText("租赁信息");

        ImageView back = (ImageView) findViewById(R.id.nav_ico_back);
        back.setOnClickListener(this);

        ImageView more = (ImageView) findViewById(R.id.nav_ico_more);
        more.setImageResource(R.drawable.nav_ico_add);
        more.setOnClickListener(this);

        listView = (AutoListView) findViewById(R.id.parking_lease_list);
        mAdapter = new LeaseListAdapter(this);
        listView.setAdapter(mAdapter);
        listView.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View v, int pos,
                    long arg3) {
                if (pos == 0 || pos >= mAdapter.getCount()) //header or footer
            		return;
                Intent i = new Intent(me, LeaseShowActivity.class);
                LeaseItem item = (LeaseItem)mAdapter.getItem(pos-1);
                Bundle bundle = new Bundle();
                bundle.putParcelable("item", item);
                i.putExtras(bundle);
                startActivity(i);
            }

        });
        listView.setOnRefreshListener(this);
        listView.setOnLoadListener(this);
        listView.setPageSize(PAGE_SIZE);
        initView();

        this.onRefresh();
    }
    
    private void initView() {
    	Spinner area = (Spinner) findViewById(R.id.area_spinner);
        ArrayAdapter<String> areaAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mAreaArr);
        areaAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        area.setAdapter(areaAdapter);
        area.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
                if (!mArea.equals(mAreaArr[arg2]))
                	return;
                mArea = mAreaArr[arg2];
                onRefresh();
            }
            public void onNothingSelected(AdapterView<?> arg0){
                //
            }
        });
    	Spinner filter = (Spinner) findViewById(R.id.filter_spinner);
        ArrayAdapter<String> filterAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mFilterArr);
        filterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        filter.setAdapter(filterAdapter);
        filter.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
            	if (mFilter == arg2)
            		return;
                mFilter = arg2;
                onRefresh();
            }
            public void onNothingSelected(AdapterView<?> arg0){
                //
            }
        });
    	Spinner order = (Spinner) findViewById(R.id.order_spinner); 
        ArrayAdapter<String> orderAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, mOrderArr);
        orderAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        order.setAdapter(orderAdapter);
        order.setOnItemSelectedListener(new Spinner.OnItemSelectedListener(){
            public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3){
            	if (mOrder == arg2)
            		return;
                mOrder = arg2;
                onRefresh();
            }
            public void onNothingSelected(AdapterView<?> arg0){
                //
            }
        });
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
        case R.id.nav_ico_back:
            finish();
            break;
        case R.id.nav_ico_more:
            Intent i = new Intent(this, LeaseEditActivity.class);
            startActivity(i);
            break;
        default:
            break;
        }
    }

    private class ViewHolder {
        TextView title;
        TextView price;
        TextView date;
    }

    private class LeaseListAdapter extends BaseAdapter {
        private LayoutInflater inflater = null;

        public LeaseListAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return mLeaseList.size();
        }

        @Override
        public Object getItem(int position) {
        	Utils.log("get " + position);
            return mLeaseList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.lease_item, null);
                holder.title = (TextView) convertView
                        .findViewById(R.id.lease_title);
                holder.price = (TextView) convertView
                        .findViewById(R.id.lease_price);
                holder.date = (TextView) convertView
                        .findViewById(R.id.publish_date);

                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            LeaseItem item = (LeaseItem) getItem(position);
            if (item != null) {
                holder.title.setText(item.name);
                holder.price.setText(Utils.getFormatNumber(item.price));
                holder.date.setText(item.date);
            }
            return convertView;
        }
    }
    
    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
			if (msg.arg1 == HttpRequest.NET_SUCCESS) {
				HttpResult ret = (HttpResult) msg.obj;
				if (ret != null && ret.status == HttpResult.STATUS_SUCCESS) {
					ArrayList<LeaseItem> got = LeaseItem.fromJsonArray(ret.body);
					if (got != null) {
			            switch (msg.what) {
			            case AutoListView.REFRESH:
			                listView.onRefreshComplete();
			                mLeaseList.clear();
			                mLeaseList.addAll(got);
			                break;
			            case AutoListView.LOAD:
			                listView.onLoadComplete();
			                mLeaseList.addAll(got);
			                break;
			            }
			            listView.setResultSize(got.size());
			            mAdapter.notifyDataSetChanged();
						return;
					}
				}
				if (ret != null)
					Utils.log(ret.msg);
			}
            mLeaseList.clear();
            listView.setResultSize(0);
            mAdapter.notifyDataSetChanged();
			ParkingApp.showToast("网络错误，请稍后再试");
        }
    };

    private void getParkings(int what) {
    	int start = 0;

    	if (what == AutoListView.LOAD) {
    		start = mLeaseList.size();
    	}

		JSONObject json = new JSONObject();
		try {
			json.put("uid", ParkingApp.mUid);
			json.put("start", start);
			json.put("counts", PAGE_SIZE);
			json.put("sort", mOrderKey[mOrder]);
			json.put("city", mArea);
			if (mFilter != 0)
				json.put("filter", mFilterKey[mFilter]);
		} catch (JSONException e1) {
			e1.printStackTrace();
			return;
		}

		HttpRequest req = new HttpRequest(ParkingApp.url_get_carports, what, json.toString(), handler);
		HttpClientUtil.post(req);
    }

    @Override
    public void onLoad() {
        // TODO Auto-generated method stub
    	getParkings(AutoListView.LOAD);
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
    	getParkings(AutoListView.REFRESH);
    }
}
